<template>
  <div class="scanner">
    <van-nav-bar title="RFID扫描" left-text="返回" @click-left="onClickLeft"></van-nav-bar>
    <van-row type="flex" justify="center">
      <van-col span="24">
        <van-form class="common-form">
          <van-cell-group class="login_form">
            <van-field :label-width="100" label="本次操作总件数" v-model="sumQty" readonly />
            <van-field :label-width="100" label="当前托盘SKU数" v-model="palletSkuQty" readonly />
            <van-field :label-width="100" label="当前托盘总件数" v-model="palletQty" readonly />
            <van-field
              v-model="palletNo"
              is-link
              readonly
              clickable
              label="托盘号"
              placeholder="点击选择托盘"
              @click="showPopups.showPalletNo = true"
            />
            <van-popup v-model="showPopups.showPalletNo" round position="bottom">
              <van-picker
                show-toolbar
                :columns="palletNoList"
                @confirm="onConfirm"
                @cancel="showPopups.showPalletNo = false"
              />
            </van-popup>
            <van-field
              id="rfidValue"
              ref="rfidValue"
              v-model="rfidValue"
              rows="2"
              label="RFID"
              type="textarea"
              :label-width="40"
              @click="rfidValueFocusClick"
              :readonly="rfidValueReadOnly"
              @focus="rfidValueFocusClick"
            />
          </van-cell-group>
        </van-form>
      </van-col>
    </van-row>
    <van-row  type="flex" justify="center" class="group_btn">
      <van-col span="10">
        <van-button
          class="reset_btn"
          type="primary"
          loading-type="spinner"
          block
          @click="reset"
          >重置</van-button
        >
      </van-col>
      <van-col span="4">
      </van-col>
      <van-col span="10">
        <van-button
          class="submit_btn"
          type="primary"
          loading-type="spinner"
          block
          @click="submit"
          >提交</van-button
        >
      </van-col>
    </van-row>
    <van-row  type="flex" justify="center" class="group_btn">
      <van-col span="24">
        <van-button
          class="reset_btn"
          type="primary"
          loading-type="spinner"
          block
          @click="save"
          >结束操作</van-button
        >
      </van-col>
    </van-row>
  </div>
</template>
<script>
import {mapGetters} from "vuex";
import { saveRfidScanData } from "@/api/rfidScan/rfidScan.js";
export default {
  name: "rfidScan",
  computed: {
    ...mapGetters("user", ["userData"]),
    ...mapGetters("scanner", ["pdaScanData"])
  },
  data() {
    return {
      user:"",
      // 总件数
      sumQty:0,
      palletQty:0,
      palletSkuQty:0,
      palletNo:1,
      showPopups: {
        showPalletNo: false
      },
      palletNoList:[],

      rfidValueReadOnly:false,
      rfidValue: "",
      // 解码TagId，默认为 SGTIN类型的 EPC
      // barcode结果 = companyPrefix（数值，首位消 0） + itemReference + checkDigit
      list:[],
      rfidObj: {
        // 校验位
        checkDigit:"",
        // 公司前缀
        companyPrefix:"",
        // EPC模式
        epcScheme:"",
        // 项目参考号
        itemReference:"",
        // RFID标签
        rfidTag:"",
        // 托盘号
        palletNo:""
      }
    };
  },
  beforeDestroy() {
    this.rfidValue = "";
  },
  created() {
    this.rfidValueFocus();
    this.palletNoList = [1];
    // 获取当前登录用户名
    this.user = this.userData.sysUserLoginName;
  },
  watch: {
    pdaScanData: {
      handler(data) {
        let input = document.activeElement.id;
        if (input == "rfidValue" && data.data != "null") {
          let arr = [];
          arr = JSON.parse(data.data);
          // 列表新增，并赋值
          this.addRfidScanList(arr)
        }
      },
      deep: true
    }
  },
  methods: {
    //点击或失焦
    rfidValueFocusClick() {
      this.rfidValueReadOnly = true;
      setTimeout(() => {
        this.rfidValueReadOnly = false;
      }, 200);
    },
    rfidValueFocus() {
      this.$nextTick(() => {
        this.$refs.rfidValue.focus();
      });
    },
    // 提交
    submit() {
      let num = Number(this.palletNoList[this.palletNoList.length - 1]);
      // 取最大值
      this.palletNo = num + 1;

      this.palletNoList.push(this.palletNo);

      // 获取对应托盘的值
      this.formatRfidValue(this.palletNo);

      this.rfidValueFocus();
    },
    reset() {
      this.rfidValue = "";
      // 清掉当前托盘的所有数据
      let newList = [];
      let palletNo = this.palletNo;
      this.list.forEach(function(item,index){
        if (item.palletNo != palletNo) {
          newList.push(item);
        }
      })
      this.list = newList;
      this.sumQty = this.list.length;
      this.palletQty = 0;
      this.palletSkuQty = 0;

      this.rfidValueFocus();
    },
    // 返回上一级页面
    onClickLeft() {
      this.$router.push({
        path: "/home/index"
      });
    },

    // 选择托盘号
    onConfirm(value) {
      this.palletNo = value;
      this.showPopups.showPalletNo = false;
      this.rfidValueFocus()

      // 获取对应托盘的值
      this.formatRfidValue(this.palletNo);
    },
    // 去重
    arrayToDistinct(array, rfidTag) {
      const res = new Map();
      return array.filter((array) => !res.has(array[rfidTag]) && res.set(array[rfidTag], 1));
    },
    // 保存结果 
    save(){
      let data = this.arrayToDistinct(this.list, 'rfidTag');
      if (data.length <= 0) {
        this.$toast.fail("暂无可保存的扫描数据");
        return;
      }
      saveRfidScanData(data)
        .then(response => {
          if (response.data.status) {
            this.$toast.success(response.data.message);

            this.palletNoList = [1];
            this.palletNo = 1;
            this.list = [];
            this.sumQty = 0;
            this.palletQty = 0;
            this.palletSkuQty = 0;
            this.rfidValue = "";
          } else {
            this.$toast.fail(response.data.message);
          }
          this.rfidValueFocus()
        })
        .catch(() => {
          this.$toast.fail("请求出错");
        });
    },

    // 添加扫描List
    addRfidScanList(arr){
      let obj = {}
      arr.forEach((item) =>{
          // 添加托盘号属性
        obj.companyPrefix = item.companyPrefix;
        obj.itemReference = item.itemReference;
        obj.checkDigit = item.checkDigit;
        obj.rfidTag = item.rfidTag;
        obj.palletNo = this.palletNo;
        obj.user = this.user;
        this.list.push(obj);
        
      })
      this.list = this.arrayToDistinct(this.list, 'rfidTag')
      // 当前总数
      this.sumQty = this.list.length;

      this.formatRfidValue(this.palletNo);
    },

    // 格式化RFID显示结果
    formatRfidValue(palletNo){
      let result = [];
      let barCodeArr = [];
      let palletQty = 0;
      let that = this;
      // 遍历目标列表
      this.list.forEach(function(item,index){
        // 只显示对应托盘SKU的数据
        if (item.palletNo == palletNo) {
          let barCode = "";
          barCode = (Number(item.companyPrefix) + "") + item.itemReference + item.checkDigit;
          item.barCode = barCode;
          if (barCodeArr.indexOf(barCode) == -1) {
            barCodeArr.push(barCode);
          }

          palletQty = palletQty + 1;
        }
      })

      // 当前托盘总数
      this.palletQty = palletQty;
      // 当前托盘SKU总数
      this.palletSkuQty = barCodeArr.length;

      // 遍历barcode列表，汇总对应数量
      barCodeArr.forEach(function(barCode,indexOut){
        let sum = 0;
        that.list.forEach(function(item,index){
          // 只显示对应托盘的数据
          if (item.palletNo == palletNo) {
            if (barCode == item.barCode) {
              sum += 1;
            }
          }  
        })
        let value = barCode + ", " + sum;
        result.push(value);
      })
      // 赋值
      this.rfidValue = result.join("\n");
    }
  }
};
</script>

<style lang="less">
// .login_form {
//     //position: relative;
//     margin: 5px;
// }

.group_btn {
    padding: 5px;
}

// .reset_btn {
//     margin-top: 10px;
// }

// .submit_btn {
//     margin-top: 10px;
// }
.footer {
    height: 1rem;
}
</style>
